<!-- 轮播设置 -->
<template>
  <div class="carousel sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="展示位置:">
              <el-select v-model="query.position" placeholder="请选择" clearable>
                <el-option label="首页" :value="0" />
                <el-option label="专区" :value="1" />
                <el-option label="积分商城" :value="2" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="轮播数据" icon="ScaleToOriginal" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table :data="dataList" max-height="493" border>
          <el-table-column label="轮播图" prop="img" align="center">
            <template #default="{row}">
              <div class="img-cell">
                <el-image :src="row.img + '?x-oss-process=image/resize,m_fill,h_80,w_120'"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title" align="center"></el-table-column>
          <el-table-column label="轮播位置" prop="position" align="center">
            <template #default="{row}">
              <span v-if="row.position === 0">首页</span>
              <span v-else-if="row.position === 1">专区</span>
              <span v-else>积分商城</span>
            </template>
          </el-table-column>
          <el-table-column label="链接类型" prop="linkType" align="center">
            <template #default="{row}">
              <span>{{ row.linkType ? '商品' : 'URL链接' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="关联商品/地址" prop="linkAddr" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已启用' : '未启用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="有效时间" prop="dictDesc" align="center" width="350">
            <template #default="{row}">
              {{ row.startTime + '至' + row.endTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.carouselId)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.carouselId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="form.carouselId ? '编辑' : '新增'" top="10vh" width="30%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-width="95px">
        <el-form-item label="标题:" prop="title" required>
          <el-input v-model="form.title" placeholder="请输入标题" clearable/>
        </el-form-item>
        <el-form-item label="位置:" prop="position">
          <el-select v-model="form.position" @change="selectChange">
            <el-option label="首页" :value="0" />
            <el-option label="专区" :value="1" />
            <el-option label="积分商城" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.position === 1" label="专区:" prop="zoneId" required>
          <el-select v-model="form.zoneId" placeholder="请选择专区">
            <el-option label="专区1" value="0" />
            <el-option label="专区2" value="1" />
            <el-option label="专区3" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="链接类型:" prop="linkType">
          <el-select v-model="form.linkType" @change="selectChange">
            <el-option label="URL" :value="0" />
            <el-option label="商品" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.linkType" label="商品" prop="linkAddr" required>
          <el-input v-model="form.productName" placeholder="请选择商品" clearable>
            <template v-if="form.linkType" #append>
              <div style="cursor: pointer;" @click="toChooseGoods">选择商品</div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-else label="URL" prop="linkAddr" required>
          <el-input v-model="form.linkAddr" placeholder="请输入链接URL" clearable></el-input>
        </el-form-item>
        <el-form-item label="有效时间:">
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker v-model="form.startTime" type="datetime" placeholder="请选择开始时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker v-model="form.endTime" type="datetime" placeholder="请选择结束时间" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="状态:" prop="enableStatus">
          <el-radio-group v-model="form.enableStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="轮播图" prop="img" required>
          <img-cutter v-model="form.img" :multiple="false" :isCard="true" width="120" height="80" ref="imgCutterRef"></img-cutter>
        </el-form-item>
      </el-form>
      <el-dialog class="append-to-body-dialog" v-model="innerShow" title="选择商品" width="70%" center draggable append-to-body>
        <div class="search-box">
          <el-form :model="queryGoods" inline size="default" label-width="80px">
            <el-form-item label="商品名称:">
              <el-input v-model="queryGoods.name" placeholder="请输入商品名称" clearable/>
            </el-form-item>
            <el-form-item label="商品编号:">
              <el-input v-model="queryGoods.productCode" placeholder="请输入商品编号" clearable/>
            </el-form-item>
            <el-form-item label="商品分类:">
              <el-select v-model="queryGoods.parentCategoryId" placeholder="请选择商品Ⅰ级分类" clearable class="input-w" @change="loadGoodsType1">
                <el-option v-for="item in goodTypesOne" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
              </el-select>
              <el-select v-model="queryGoods.subCategoryId" placeholder="请选择商品Ⅱ级分类" clearable class="input-w">
                <el-option v-for="item in goodTypesTwo1" :key="item.productCategoryId" :label="item.name" :value="item.productCategoryId"/>
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="loadGoods(1)">查询</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch(false)">重置</el-button>
          </div>
        </div>
        <el-table ref="tableRef" :data="goodsList" max-height="493" border>
          <el-table-column label="商品图片" prop="pic" align="center">
            <template #default="{row}">
              <div class="img-cell">
                <el-image :src="row.pic" :preview-src-list="[row.pic]" preview-teleported/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
          <el-table-column label="商品货号" prop="productCode" align="center"></el-table-column>
          <el-table-column label="销售价" prop="salePrice" align="center"></el-table-column>
          <el-table-column label="操作" prop="serviceName" align="center">
            <template #default="{row}">
              <el-button type="primary" @click="doChooseGoods(row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="queryGoods.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="queryGoods.current" 
          :page-size="queryGoods.size"
          :total="queryGoods.total"
          @current-change="loadGoods"
          @size-change="sizeChangeGoods">
        </el-pagination>
      </el-dialog>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="carousel">
  import { cudCarouselApi, getCarouselPagesApi, getCarouselInfoApi, getGoodsListPagesApi, getGoodsTypeListApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  // 获取form表单的ref 
  const formRef = ref(null)
  const imgCutterRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    innerShow: false,
    query: {
      position: '',
      current: 1,
      size: 20,
      total: 0
    },
    queryGoods: {
      name: '',
      productCode: '',
      parentCategoryId: '',
      subCategoryId: '',
      enableStatus: '1',
      current: 1,
      size: 20,
      total: 0
    },
    goodTypesOne: [],
    goodTypesTwo: [],
    dataList: [],
    goodsList: [],
    form: {
      carouselId: '',
      title: '',
      position: 0,
      zoneId: '',
      linkType: 1,
      linkAddr: '',
      startTime: '',
      endTime: '',
      enableStatus: 1,
      img: '',
      productName: ''
    },
    rules: {
      title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
      zoneId: [{ required: true, message: '请选择专区', trigger: ['blur', 'change'] }],
      linkAddr: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value.length) {
              callback(new Error(`${form.value.linkType ? '请选择商品' : '请输入链接URL'}`))
            } else {
              callback()
            }
          } 
        }
      ],
      img: [{ required: true, message: '请上传轮播图', trigger: ['blur', 'change'] }]
    }
  })
  let {loading, show, innerShow, query, queryGoods, goodTypesOne, goodTypesTwo, dataList, goodsList, form, rules} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getCarouselPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 查询新增抵扣数据弹窗中的商品列表数据
  function loadGoods(page) {
    currentData.loading = true
    currentData.queryGoods.current = page
    getGoodsListPagesApi(currentData.queryGoods).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.goodsList = res.data.pages
        currentData.queryGoods.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  /**
   * 查询商品分类下拉列表数据
   * parentId为0或不传时候，查询的是一级商品分类，其他情况查询是二级商品分类
   */
  function loadGoodsType(parentId) {
    if(!parentId) {
      currentData.goodTypesTwo = []
      currentData.queryGoods.subCategoryId = ''
      return
    }
    getGoodsTypeListApi({parentId: parentId}).then(res => {
      if(res.code === '200') {
        if(parentId === '0') {
          currentData.goodTypesOne = res.data
        } else {
          currentData.goodTypesTwo = res.data
          currentData.queryGoods.subCategoryId = ''
        }
      }
    })
  }
  loadGoodsType

  // 重置查询
  function resetSearch() {
    currentData.query.position = ''
    load(1)
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.carouselId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.carouselId ? '修改' : '新增'}`)
          cudCarouselApi(`${currentData.form.carouselId ? 'update' : 'save'}`, currentData.form).then(res => { // 修改
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              if(currentData.form.carouselId) {
                load(currentData.query.current)
              } else {
                load(1)
              }
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 修改前弹窗
  function toUpdate(carouselId) {
    // 根据码表id查询用户信息
    getCarouselInfoApi(carouselId).then(res => {
      if(res.code === '200') {
        currentData.form = res.data
        currentData.show = true
      } else {
        currentThis.$message.error('获取轮播图信息失败')
      }
    })
  }

  // 删除
  function doDelete(carouselId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('删除中，请耐心等待')
      cudCarouselApi('delete', { id: carouselId }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  function selectChange() {
    formRef.value.validate((valid) => {})
  }

  function toChooseGoods() {
    loadGoods(1)
    currentData.innerShow = true
  }

  // 新增编辑弹窗重置数据
  function resetForm() {
    currentData.form = {
      carouselId: '',
      title: '',
      position: 0,
      zoneId: '',
      linkType: 1,
      linkAddr: '',
      startTime: '',
      endTime: '',
      enableStatus: 1,
      img: '',
      productName: ''
    }
    imgCutterRef.value.resetImgCutter()
    formRef.value.resetFields()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  function sizeChangeGoods(size) {
    currentData.queryGoods.size = size
    loadGoods(1)
  }

  onActivated(() => {
    load(currentData.query.current)
    loadGoodsType('0')
  })
</script>

<style lang="less" scoped>
.carousel{
  :deep(.el-table) {
    .img-cell{
      display: flex;
      justify-content: center;
      align-items: center;
      .el-image{
        width: 120px; 
        height: 80px;
        border-radius: 5px;
      }
    }
  }
  :deep(.el-dialog){
    .el-input{
      width: 300px;
    }
    .text-center{
      text-align: center;
    }
  }
}
</style>